package com.asiainfo.heshanghui.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.asiainfo.heshanghui.adapter_recyclerview.HorizontalDividerItemDecoration2;
import com.asiainfo.heshanghui.adapter_recyclerview.UniversalAdapter;
import com.asiainfo.heshanghui.configs.ConstantsME;
import com.asiainfo.heshanghui.configs.EventBusTag;
import com.asiainfo.heshanghui.configs.InterfaceConfig;
import com.asiainfo.heshanghui.entity.StoreInfo;
import com.asiainfo.heshanghui.networkModel.HttpUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.framework.Utils.PreferencesHelper;
import com.framework.Utils.ScreenUtils;
import com.framework.Utils.Utils;
import com.framework2.base.BiuooBaseActivity;
import com.framework2.customview.TitleView;
import com.framework2.utils.BiuooCollectionUtil;
import com.framework2.utils.BiuooCustomProgressDialogUtils;
import com.asiainfo.heshanghui.R;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 入库 搜索
 *
 * @author Yangjie
 *         className PutInStoreSearchActivity
 */
public class PutInStoreSearchActivity extends BiuooBaseActivity implements View.OnClickListener{


    @BindView(R.id.titleView)
    TitleView titleView;
    @BindView(R.id.etSearch)
    EditText etSearch;
    @BindView(R.id.tvSearch)
    TextView tvSearch;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private UniversalAdapter adapter;
    private List<StoreInfo> storeInfoList = new ArrayList<>();
    private boolean requestSuccess;
    private int page = 1;
    private int pageSize = 300;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_put_in_store_search);
        ButterKnife.bind(this);
        Utils.setTranslucentStatus(this, true);
        Utils.setStatusBarTintColor(this,
                getResources().getColor(R.color.white));
        initView();
        initEvent();
        initRecyclerView();
    }


    //eventBus通知新消息
    @Subscribe(threadMode = ThreadMode.MAIN, tag = EventBusTag.GOODS_TYPE)
    public void receivedNewMessage(String info) {
    }

    private void initView() {
        titleView.setTitle("搜索");
    }

    private void initEvent() {
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tvSearch.setVisibility(TextUtils.isEmpty(s) ? View.INVISIBLE : View.VISIBLE);
            }
        });
    }

    @SuppressWarnings("unchecked")
    private void initRecyclerView() {
        //第一种，简单的颜色，高度,水平分割线
        HorizontalDividerItemDecoration2 horizontalDividerItemDecoration = new HorizontalDividerItemDecoration2(PutInStoreSearchActivity.this);
        horizontalDividerItemDecoration.setColor(this, R.color.gray);
        horizontalDividerItemDecoration.setDividerHeightPx(1);
        recyclerView.addItemDecoration(horizontalDividerItemDecoration);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

//        if (BiuooCollectionUtil.getInstance().isEmpty(storeInfoList)) {
//
//        }
        adapter = initAdapter(adapter);
        recyclerView.setAdapter(adapter);
    }

    /**
     * @param adapter adapter
     * @return UniversalAdapter
     */
    @SuppressWarnings("unchecked")
    private UniversalAdapter initAdapter(UniversalAdapter adapter) {
        final DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance();
        decimalFormat.applyPattern("0.00");
        if (adapter == null) {
            adapter = new UniversalAdapter<StoreInfo>(PutInStoreSearchActivity.this, R.layout.listitem_store, storeInfoList) {
                @Override
                protected void getItemView(UniversalViewHolder viewHolder, final StoreInfo info, int position) {
                    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, (int) ((ScreenUtils.getInstance().getScreenHeightPx(PutInStoreSearchActivity.this) - ScreenUtils.getInstance().getStatusBarHeightPx(PutInStoreSearchActivity.this) - ScreenUtils.getInstance().dip2px(PutInStoreSearchActivity.this, 50)) * 0.11));
                    viewHolder.itemView.setLayoutParams(params);
                    SpannableString spannableString = new SpannableString(info.getCount() + (info.getProductType() == 1 ? "台" : "件"));
                    spannableString.setSpan(new AbsoluteSizeSpan(10, true), String.valueOf(info.getCount()).length(), spannableString.length(),
                            Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                    viewHolder.setText(R.id.tv_count, spannableString);
                    viewHolder.setText(R.id.tv_name, info.getName());
                    ImageView imageView = viewHolder.getView(R.id.iv_icon);
                    Glide.with(PutInStoreSearchActivity.this).load(info.getImgUrl()).placeholder(R.mipmap.default_icon).error(R.mipmap.default_icon)
                            .priority(Priority.HIGH).into(imageView);
//                    viewHolder.setText(R.id.tv_price, "建议售价:" + decimalFormat.format(info.getPrice()) + "元");
                }
            };
        }
        return adapter;
    }


    private void requestStoreSearchList(int type, String keyword) {
//        if (TextUtils.isEmpty(PreferencesHelper.getInstance().getStringData(ConstantsME.currentShopId))) {
//            ConstantRequestUtil.getInstance().requestJustShopIds(this);
//            Utils.h.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    requestStoreList_();
//                }
//            }, 100);
//        } else {
        requestStoreSearchList_(type,keyword);
//        }
    }

    private void requestStoreSearchList_(int type,String keyword) {

        storeInfoList.clear();
        adapter.notifyDataSetChanged();
        HttpUtil.getInstance().requestStoreList(this, InterfaceConfig.storeSearchList, PreferencesHelper.getInstance().getStringData(ConstantsME.currentShopId), type, keyword, page, pageSize, new HttpUtil.OnRequestListResult<StoreInfo>() {
            @Override
            public void onSuccess(List<StoreInfo> list, String... msg) {
                requestSuccess = true;
                BiuooCustomProgressDialogUtils.dismissProcessDialog();
                if (!BiuooCollectionUtil.getInstance().isEmpty(list)) {
                    if (page == 1) {
                        storeInfoList.clear();
                    }
                    storeInfoList.addAll(list);
                    adapter.notifyDataSetChanged();
                } else if (page == 1 || BiuooCollectionUtil.getInstance().isEmpty(storeInfoList)) {
                    page = 1;
                }
                try {
                    String totalCount = msg[0];
                    int totalCount_ = Integer.parseInt(totalCount);
                } catch (Exception e) {
                }
            }

            @Override
            public void onFail(int code, String msg) {
                BiuooCustomProgressDialogUtils.dismissProcessDialog();
                if (page == 1) {
                    storeInfoList.clear();
                }
            }
        });
    }

    @OnClick(R.id.tvSearch)
    public void onViewClicked() {
        BiuooCustomProgressDialogUtils.showProcessDialog(this,"正在搜索");
        requestStoreSearchList(0,etSearch.getText().toString());
    }

    @Override
    public void onClick(View v) {

    }
}
